import { serve } from '@hono/node-server'
import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { logger } from 'hono/logger'
import { prettyJSON } from 'hono/pretty-json'
import { secureHeaders } from 'hono/secure-headers'
import { timing } from 'hono/timing'

import { config } from '@/config/env'
import { errorHandler } from '@/middleware/errorHandler'
import { requestLogger } from '@/middleware/requestLogger'
import { metricsMiddleware } from '@/middleware/metrics'

// 路由导入
import authRoutes from '@/routes/auth'
import pluginRoutes from '@/routes/plugins'
import developerRoutes from '@/routes/developer'
import adminRoutes from '@/routes/admin'
import healthRoutes from '@/routes/health'
import apiKeyRoutes from '@/routes/apiKeys'
import securityRoutes from '@/routes/security'
import signatureRoutes from '@/routes/signature'
import advancedSecurityRoutes from '@/routes/advancedSecurity'
import { rateLimiter } from './middleware/rateLimiter'

// 创建 Hono 应用
type Env = {
  Bindings: {}
  Variables: {}
}
const app = new Hono<Env>()

// 全局中间件
app.use('*', timing() as any)
app.use('*', logger() as any)
app.use('*', requestLogger() as any)
app.use('*', secureHeaders() as any)
app.use('*', prettyJSON() as any)

// CORS 配置
app.use('*', cors({
  origin: config.cors.origins,
  credentials: true,
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
  allowHeaders: ['Content-Type', 'Authorization', 'X-API-Key', 'X-Requested-With'],
  exposeHeaders: ['X-Total-Count', 'X-Page-Count'],
  maxAge: 86400 // 24小时
}) as any)

// 限流中间件 (暂时注释，需要Redis)
app.use('/api/*', rateLimiter())

// 监控指标中间件
app.use('*', metricsMiddleware())

// 健康检查路由 (不需要版本前缀)
app.route('/health', healthRoutes)
app.route('/metrics', healthRoutes) // Prometheus metrics

// API 路由 (带版本前缀)
const apiV1 = new Hono()

// 认证中间件 (支持JWT和API密钥)
import { authMiddleware, optionalAuthMiddleware, hybridAuthMiddleware, adminMiddleware } from '@/middleware/auth'

// 对插件查询使用可选认证
apiV1.use('/plugins/*', optionalAuthMiddleware())

// 对需要认证的路由使用混合认证中间件（支持JWT或API密钥）
apiV1.use('/developer/*', hybridAuthMiddleware())
apiV1.use('/keys/*', authMiddleware()) // API密钥管理只能用JWT
apiV1.use('/security/*', hybridAuthMiddleware())
apiV1.use('/signature/*', authMiddleware()) // 签名管理需要JWT认证
apiV1.use('/advanced-security/*', authMiddleware()) // 高级安全功能需要JWT认证

// 管理员路由需要JWT认证 + 管理员权限
apiV1.use('/admin/*', authMiddleware())
apiV1.use('/admin/*', adminMiddleware())

// 注册路由
apiV1.route('/auth', authRoutes)
apiV1.route('/plugins', pluginRoutes)
apiV1.route('/developer', developerRoutes)
apiV1.route('/admin', adminRoutes)
apiV1.route('/keys', apiKeyRoutes)
apiV1.route('/security', securityRoutes)
apiV1.route('/signature', signatureRoutes)
apiV1.route('/advanced-security', advancedSecurityRoutes)

// 挂载 API v1 路由
app.route('/api/v1', apiV1)

// 根路径
app.get('/', (c) => {
  return c.json({
    name: 'Bai-hu Cloud Platform API',
    version: '0.1.0',
    status: 'running',
    timestamp: new Date().toISOString(),
    docs: '/api/v1/docs',
    health: '/health'
  })
})

// API 文档路由
app.get('/api/v1/docs', (c) => {
  return c.json({
    title: 'Bai-hu Cloud Platform API Documentation',
    version: 'v1',
    description: 'RESTful API for Bai-hu plugin cloud platform',
    baseUrl: `${c.req.url.split('/api')[0]}/api/v1`,
    endpoints: {
      auth: {
        'POST /auth/register': 'Register new developer',
        'POST /auth/login': 'Developer login',
        'POST /auth/refresh': 'Refresh access token',
        'GET /auth/me': 'Get current user info (requires auth)',
        'GET /auth/profile': 'Get user profile',
        'PUT /auth/profile': 'Update user profile'
      },
      plugins: {
        'GET /plugins': 'List public plugins',
        'GET /plugins/:identifier': 'Get plugin details (by ID or name)',
        'GET /plugins/:name/versions': 'Get plugin versions',
        'GET /plugins/:name/download/:version': 'Download plugin package',
        'GET /plugins/:name/manifest/:version': 'Get plugin manifest'
      },
      developer: {
        'GET /developer/plugins': 'Get my plugins',
        'POST /developer/plugins': 'Create new plugin',
        'GET /developer/plugins/:id': 'Get plugin details',
        'PUT /developer/plugins/:id': 'Update plugin',
        'DELETE /developer/plugins/:id': 'Delete plugin',
        'POST /developer/plugins/:id/versions': 'Upload new version'
      },
      admin: {
        'GET /admin/plugins': 'Get pending plugins',
        'PUT /admin/plugins/:id/approve': 'Approve plugin',
        'PUT /admin/plugins/:id/reject': 'Reject plugin',
        'GET /admin/stats': 'Get system statistics'
      }
    },
    authentication: {
      jwt: 'Bearer token for web interface',
      apiKey: 'X-API-Key header for programmatic access'
    }
  })
})

// 404 处理
app.notFound((c) => {
  return c.json({
    success: false,
    error: {
      code: 'NOT_FOUND',
      message: 'The requested resource was not found',
      path: c.req.path
    }
  }, 404)
})

// 错误处理中间件
app.onError(errorHandler)

// 启动服务器
const port = config.port
const host = config.host

console.log(`🚀 Starting Bai-hu Cloud Platform API...`)
console.log(`📍 Environment: ${config.nodeEnv}`)
console.log(`🌐 Server: http://${host}:${port}`)
console.log(`📚 API Docs: http://${host}:${port}/api/v1/docs`)
console.log(`❤️  Health Check: http://${host}:${port}/health`)

serve({
  fetch: app.fetch,
  port,
  hostname: host
}, (info) => {
  console.log(`✅ Server is running on http://${info.address}:${info.port}`)
})

// 优雅关闭
process.on('SIGTERM', () => {
  console.log('🛑 SIGTERM received, shutting down gracefully...')
  process.exit(0)
})

process.on('SIGINT', () => {
  console.log('🛑 SIGINT received, shutting down gracefully...')
  process.exit(0)
})

export default app
